package com.pro.common.service.sitecontent.service;

import com.pro.framework.api.enums.EnumEnv;
import com.pro.common.service.properties.BaseProperties;
import com.pro.common.service.service.NacosConfigInitService;
import com.pro.common.service.sitecontent.dao.AuthDictDao;
import com.pro.common.service.sitecontent.model.db.AuthDict;
import com.pro.framework.mybatisplus.BaseService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * 国家 服务实现类
 */
@Service
@AllArgsConstructor
public class AuthDictService extends BaseService<AuthDictDao, AuthDict> {
    private NacosConfigInitService nacosConfigInitService;
    private BaseProperties baseProperties;

    @Override
    public boolean updateById(AuthDict entity) {
        EnumEnv env = baseProperties.getCommonEnv();
        String dataId = "global-" + env + ".yaml";
        // 查询配置
        String configContents = nacosConfigInitService.getConfig(dataId);
        // 修改配置(在现有的基础上)
        configContents = modifyYaml(configContents, (yamlMap) -> {
            // 获取或创建common节点
            //noinspection unchecked
            Map<String, Object> commonMap = (Map<String, Object>) yamlMap.computeIfAbsent(
                    "common", k -> new LinkedHashMap<>()
            );
            //noinspection unchecked
            Map<String, Object> authDictMap = (Map<String, Object>) commonMap.computeIfAbsent(
                    "authDictMap", k -> new LinkedHashMap<>()
            );
            // 添加/修改 某个字典的值
            authDictMap.put(entity.getCode(), entity.getValue());
        });
        // 保存配置
        nacosConfigInitService.updateCenterConfig(dataId, configContents);
        return super.updateById(entity);
    }

    /**
     * 修改YAML内容字符串
     *
     * @param yamlContent 原始YAML内容
     * @return 修改后的YAML内容
     */
    public static String modifyYaml(String yamlContent, Consumer<Map<String, Object>> yamlMapConsumer) {
        // 使用Spring的YAML解析器
        YamlMapFactoryBean yamlFactory = new YamlMapFactoryBean();
        yamlFactory.setResources(new ByteArrayResource(yamlContent.getBytes()));
        Map<String, Object> yamlMap = yamlFactory.getObject();

        if (yamlMap == null) {
            yamlMap = new LinkedHashMap<>();
        }

        yamlMapConsumer.accept(yamlMap);

        // 使用Spring自带的YAML输出（实际内部还是使用SnakeYAML）
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        options.setPrettyFlow(true);

        return new Yaml(options).dump(yamlMap);
    }
}
